<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Amazon extends Backend {

	public function __construct()
	{
		parent::__construct();
        $this->load->model(['category_model','goods_model']);
		//
		$this->data['page_home']  = lang('lang_dashboard');
		$this->data['page_title'] = '导入数据';
	}


	public function index()
	{
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			$this->data['page_title'] => 'backend/about'
		);

        $this->form_validation->set_rules('shopkey', '请输入店铺密钥', 'required');
        //$this->form_validation->set_rules('excelfilename', '请选择Excel文件', 'required');

        $mosmessage="";
        if ($this->form_validation->run() == TRUE && !empty($_FILES))
        {
            $shop=$this->category_model->get_item_by_key($this->input->post("shopkey"));
            if(!$shop)
            {
                $mosmessage="店铺密钥错误，无法匹配，请检查!";
            }
            else
            {
                ini_set("memory_limit","200M");
                $dirpath='./upload/tmp/'.date("Ym")."/";
                mkdirs($dirpath);
                $config['upload_path']      = $dirpath;
                $config['allowed_types']    = 'csv';
                $config['file_name'] = uniqid();

                $this->load->library('upload', $config);
                $result = $this->upload->do_upload('xlsxfile');
                if($result)
                {

                    $info = $this->upload->data();
                    $inputFileName=$dirpath.$info["orig_name"]; 
                    $this->load->library('parsecsv');
                    $this->parsecsv->auto($inputFileName);

                    $newproduct = [];
                    foreach ($this->parsecsv->data as $row) {
                        $tmp=array_values($row);
                        if($tmp[11]=="Parent")
                        {
                            if($newproduct)
                            {
                                $res[]=$newproduct;
                            }
                            $newproduct=[
                                "sku"=>$tmp[3],
                                "name"=>$tmp[2],
                                "url"=>$tmp[19],
                                "img"=>explode("|",$tmp[21]),
                                "price"=>$tmp[6],
                                "desc"=>$tmp[24],
                                "sales"=>$tmp[10],
                                "color"=>[],
                                "size"=>[],
                                "colorimg"=>[],
                            ];
                            $newproduct["name"]=trim(str_replace($tmp[1],"",$newproduct["name"]));

                            if(!empty($tmp[25]) && $tmp[25]!="-")
                            {
                                $newproduct["desc"]=$tmp[25];
                            }
                            $newproduct["desc"]=trim(str_replace($tmp[1],"",$newproduct["desc"]));
                        }
                        else
                        {
                            if($tmp[14])
                            {
                                $size=$tmp[14];
                                if(!in_array($size,$newproduct["size"]))
                                {
                                    $newproduct["size"][]=$size;
                                }
                            }
                          
                            if($tmp[13])
                            {
                                $color=$tmp[13];
                                if(!in_array($color,$newproduct["color"]))
                                {
                                    $newproduct["color"][]=$color;
                                    $tmpimg=explode("|",$tmp[21]);
                                    if(in_array($tmpimg[0],$newproduct["img"]))
                                    {
                                        $key=array_search($tmpimg[0],$newproduct["img"]);
                                        array_splice($newproduct["img"],$key,1);
                                    }
                                    $newproduct["colorimg"][]=$tmpimg[0];
                                }
                            }                            
                        }
                        
                    }
                    $res[]=$newproduct;

                    $pcount=0;
                    foreach($res as $r)
                    {
                        if($this->goods_model->getbytbid($r["sku"],$shop["id"]))
                        {
                            continue;
                        }
                        $product=array(
                            "catid"=>$shop["id"],
                            "tbid"=>$r["sku"],
                            "name"=>$r["name"],
                            "thumb"=>serialize($r["img"]),
                            "source"=>"amazon",
                            "source_url"=>$r["url"],
                            "price"=>$r["price"],
                            "sales"=>$r["sales"],
                            "desc"=>$r["desc"],
                            "tags"=>""
                        );
                        $prop=array();
                        if($r["color"])
                        {
                            $prop["vv"][]=array("name"=>"Color","value"=>$r["color"],"image"=>$r["colorimg"]);
                        }
                        if($r["size"])
                        {
                            $prop["vv"][]=array("name"=>"Size","value"=>$r["size"]);
                        }
                        $product["option"]=serialize($prop);

                        if($this->goods_model->create($product)){
                            $pcount++;
                        }                        
                    }
                    $mosmessage="共导入".$pcount."条商品";
                }
                else
                {
                    $mosmessage = $this->upload->display_errors();
                }
            }
            
        }
        $this->data["momessage"]=$mosmessage;

		//
		$this->data['content_header_title'] = content_header_title($this->data['page_title'],'Amazon CSV导入');
		$this->data['content'] = 'amazon';

		//
		$this->render();
	}
}
